package com.finalcial.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.finalcial.po.LoginMsg;
import com.finalcial.service.UserService;
import com.finalcial.util.MD5Util;

/**
 * 用于登录
 * @author Administrator
 *
 */
@Controller
public class LoginController {
	
	@Resource
	private UserService userService;

	/**
	 * index.jsp的访问地址
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/index")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
		String value = "";//返回值
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(userName);
		System.out.println(password);
		List<Map<String,Object>> userList = userService.getUserMsg(userName, MD5Util.convertMD5(password));
		if(userList.isEmpty()){
			 value = "1";
			ModelAndView mav1 = new ModelAndView("../login","value",value);
			 return mav1;
		}else{
			LoginMsg loginMsg = userService.getLoginMsg(userName, MD5Util.convertMD5(password));
			List<Map<String, Object>> functions = userService.getFunctionByUserId(String.valueOf(loginMsg.getUserId()), "1");
			List<Map<String, Object>> fus = userService.getFunctionByUserId(String.valueOf(loginMsg.getUserId()), "9014");
			HttpSession session = request.getSession();
			session.setAttribute("LoginMsg", loginMsg);
			ModelAndView mav2 = new ModelAndView("index","userList",userList);
			mav2.addObject("functions",functions);
			mav2.addObject("fus",fus);
			return mav2;
		}

	}
	
	
	@ResponseBody
	@RequestMapping("/exit")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response){
		HttpSession session = request.getSession();
		session.removeAttribute("LoginMsg");
		//System.out.println("我进了");
		ModelAndView mav = new ModelAndView("../login");
		return mav;
	}
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getFunctionAjax", method = RequestMethod.POST)
	public Map<String, Object> getFunctionAjax(HttpServletRequest request, HttpServletResponse response){
		LoginMsg loginMsg = (LoginMsg) request.getSession().getAttribute("LoginMsg");
		System.out.println(loginMsg);
		String parent = request.getParameter("parent");
		List<Map<String, Object>> functions = userService.getFunctionByUserId(String.valueOf(loginMsg.getUserId()), parent);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("functions", functions);
		return map;
	}
	
}
